<template>
  <div class="cost-control">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">成本控制</h1>
      <p class="page-description">项目成本预算管理、费用控制和成本分析</p>
    </div>

    <!-- 成本概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon budget">
              <el-icon><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(costOverview.totalBudget) }}</div>
              <div class="card-label">总预算</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon spent">
              <el-icon><CreditCard /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(costOverview.actualCost) }}</div>
              <div class="card-label">实际支出</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon remaining">
              <div class="card-icon remaining">
                <el-icon><Wallet /></el-icon>
              </div>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(costOverview.remainingBudget) }}</div>
              <div class="card-label">剩余预算</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon variance">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ costOverview.budgetVariance }}%</div>
              <div class="card-label">预算偏差</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成本分析图表 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>成本趋势分析</span>
              <el-select v-model="trendPeriod" size="small" style="width: 120px">
                <el-option label="近7天" value="7d" />
                <el-option label="近30天" value="30d" />
                <el-option label="近3个月" value="3m" />
                <el-option label="近6个月" value="6m" />
              </el-select>
            </div>
          </template>
          <div ref="costTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card>
          <template #header>
            <span>成本分类占比</span>
          </template>
          <div ref="costCategoryChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预算管理 -->
    <el-card class="budget-section">
      <template #header>
        <div class="section-header">
          <span>预算管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showBudgetDialog = true">
              <el-icon><Plus /></el-icon>
              新增预算
            </el-button>
            <el-button @click="exportBudgetData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <div class="search-filters">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="8" :md="6">
            <el-input
              v-model="budgetFilters.keyword"
              placeholder="搜索预算项目"
              clearable
              @input="handleBudgetSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-select v-model="budgetFilters.category" placeholder="预算类别" clearable>
              <el-option label="人力成本" value="labor" />
              <el-option label="设备费用" value="equipment" />
              <el-option label="材料费用" value="material" />
              <el-option label="差旅费用" value="travel" />
              <el-option label="其他费用" value="other" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-select v-model="budgetFilters.status" placeholder="预算状态" clearable>
              <el-option label="待审批" value="pending" />
              <el-option label="已批准" value="approved" />
              <el-option label="执行中" value="executing" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="24" :md="6">
            <el-button type="primary" @click="handleBudgetSearch">搜索</el-button>
            <el-button @click="resetBudgetFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 预算列表 -->
      <el-table
        :data="filteredBudgetList"
        v-loading="budgetLoading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="预算项目" min-width="150" />
        <el-table-column prop="category" label="类别" width="100">
          <template #default="{ row }">
            <el-tag :type="getBudgetCategoryType(row.category)">{{ getBudgetCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="budgetAmount" label="预算金额" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.budgetAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实际支出" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.actualAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="variance" label="偏差" width="100">
          <template #default="{ row }">
            <span :class="{ 'text-danger': row.variance > 0, 'text-success': row.variance < 0 }">
              {{ row.variance > 0 ? '+' : '' }}{{ row.variance }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getBudgetStatusType(row.status)">{{ getBudgetStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editBudget(row)">编辑</el-button>
            <el-button size="small" type="info" @click="viewBudgetDetail(row)">详情</el-button>
            <el-button size="small" type="danger" @click="deleteBudget(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="budgetPagination.currentPage"
          v-model:page-size="budgetPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="budgetPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleBudgetSizeChange"
          @current-change="handleBudgetCurrentChange"
        />
      </div>
    </el-card>

    <!-- 费用审批 -->
    <el-card class="expense-section">
      <template #header>
        <div class="section-header">
          <span>费用审批</span>
          <div class="header-actions">
            <el-button type="primary" @click="showExpenseDialog = true">
              <el-icon><Plus /></el-icon>
              提交费用
            </el-button>
          </div>
        </div>
      </template>

      <!-- 费用审批列表 -->
      <el-table
        :data="expenseList"
        v-loading="expenseLoading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="费用标题" min-width="150" />
        <el-table-column prop="category" label="费用类别" width="100">
          <template #default="{ row }">
            <el-tag :type="getExpenseCategoryType(row.category)">{{ getExpenseCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="费用金额" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="status" label="审批状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getExpenseStatusType(row.status)">{{ getExpenseStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitDate" label="提交日期" width="120" />
        <el-table-column prop="approver" label="审批人" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewExpenseDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              size="small" 
              type="success" 
              @click="approveExpense(row)"
            >
              审批
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              size="small" 
              type="danger" 
              @click="rejectExpense(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 预算对话框 -->
    <el-dialog
      v-model="showBudgetDialog"
      :title="budgetForm.id ? '编辑预算' : '新增预算'"
      width="600px"
      @close="resetBudgetForm"
    >
      <el-form
        ref="budgetFormRef"
        :model="budgetForm"
        :rules="budgetRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="budgetForm.projectId" placeholder="选择项目" style="width: 100%">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预算项目" prop="name">
          <el-input v-model="budgetForm.name" placeholder="请输入预算项目名称" />
        </el-form-item>
        <el-form-item label="预算类别" prop="category">
          <el-select v-model="budgetForm.category" placeholder="选择预算类别" style="width: 100%">
            <el-option label="人力成本" value="labor" />
            <el-option label="设备费用" value="equipment" />
            <el-option label="材料费用" value="material" />
            <el-option label="差旅费用" value="travel" />
            <el-option label="其他费用" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算金额" prop="budgetAmount">
          <el-input-number
            v-model="budgetForm.budgetAmount"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入预算金额"
          />
        </el-form-item>
        <el-form-item label="预算周期">
          <el-date-picker
            v-model="budgetDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预算描述">
          <el-input
            v-model="budgetForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入预算描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBudgetDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBudget" :loading="budgetSaving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 费用提交对话框 -->
    <el-dialog
      v-model="showExpenseDialog"
      title="提交费用申请"
      width="600px"
      @close="resetExpenseForm"
    >
      <el-form
        ref="expenseFormRef"
        :model="expenseForm"
        :rules="expenseRules"
        label-width="100px"
      >
        <el-form-item label="费用标题" prop="title">
          <el-input v-model="expenseForm.title" placeholder="请输入费用标题" />
        </el-form-item>
        <el-form-item label="费用类别" prop="category">
          <el-select v-model="expenseForm.category" placeholder="选择费用类别" style="width: 100%">
            <el-option label="差旅费" value="travel" />
            <el-option label="餐饮费" value="meal" />
            <el-option label="交通费" value="transport" />
            <el-option label="办公用品" value="office" />
            <el-option label="培训费" value="training" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="费用金额" prop="amount">
          <el-input-number
            v-model="expenseForm.amount"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入费用金额"
          />
        </el-form-item>
        <el-form-item label="发生日期" prop="occurDate">
          <el-date-picker
            v-model="expenseForm.occurDate"
            type="date"
            placeholder="选择发生日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="费用说明">
          <el-input
            v-model="expenseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入费用说明"
          />
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            multiple
            :auto-upload="false"
            :file-list="expenseForm.attachments"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf文件，且不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showExpenseDialog = false">取消</el-button>
        <el-button type="primary" @click="submitExpense" :loading="expenseSaving">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Money,
  CreditCard,
  Wallet,
  TrendCharts,
  Plus,
  Download,
  Search,
  UploadFilled
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const costOverview = ref({
  totalBudget: 5000000,
  actualCost: 3200000,
  remainingBudget: 1800000,
  budgetVariance: -8.5
})

const trendPeriod = ref('30d')
const costTrendChart = ref()
const costCategoryChart = ref()

// 预算管理
const budgetLoading = ref(false)
const showBudgetDialog = ref(false)
const budgetSaving = ref(false)
const budgetFormRef = ref()

const budgetFilters = reactive({
  keyword: '',
  category: '',
  status: ''
})

const budgetPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const budgetList = ref([
  {
    id: 1,
    name: '开发团队人力成本',
    category: 'labor',
    budgetAmount: 1500000,
    actualAmount: 1200000,
    variance: -20,
    status: 'executing',
    startDate: '2024-01-01',
    endDate: '2024-06-30',
    projectId: 1
  },
  {
    id: 2,
    name: '服务器设备采购',
    category: 'equipment',
    budgetAmount: 800000,
    actualAmount: 850000,
    variance: 6.25,
    status: 'completed',
    startDate: '2024-02-01',
    endDate: '2024-03-31',
    projectId: 1
  },
  {
    id: 3,
    name: '软件许可证费用',
    category: 'material',
    budgetAmount: 300000,
    actualAmount: 280000,
    variance: -6.67,
    status: 'executing',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    projectId: 2
  },
  {
    id: 4,
    name: '差旅培训费用',
    category: 'travel',
    budgetAmount: 200000,
    actualAmount: 150000,
    variance: -25,
    status: 'approved',
    startDate: '2024-03-01',
    endDate: '2024-08-31',
    projectId: 2
  }
])

const budgetForm = reactive({
  id: null,
  projectId: '',
  name: '',
  category: '',
  budgetAmount: 0,
  description: '',
  startDate: '',
  endDate: ''
})

const budgetDateRange = ref([])

const budgetRules = {
  projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
  name: [{ required: true, message: '请输入预算项目名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择预算类别', trigger: 'change' }],
  budgetAmount: [{ required: true, message: '请输入预算金额', trigger: 'blur' }]
}

// 费用审批
const expenseLoading = ref(false)
const showExpenseDialog = ref(false)
const expenseSaving = ref(false)
const expenseFormRef = ref()

const expenseList = ref([
  {
    id: 1,
    title: '北京出差费用',
    category: 'travel',
    amount: 3500,
    applicant: '张三',
    status: 'pending',
    submitDate: '2024-01-15',
    approver: '',
    projectId: 1
  },
  {
    id: 2,
    title: '团队聚餐费用',
    category: 'meal',
    amount: 1200,
    applicant: '李四',
    status: 'approved',
    submitDate: '2024-01-10',
    approver: '王五',
    projectId: 1
  },
  {
    id: 3,
    title: '办公用品采购',
    category: 'office',
    amount: 800,
    applicant: '赵六',
    status: 'rejected',
    submitDate: '2024-01-08',
    approver: '王五',
    projectId: 2
  }
])

const expenseForm = reactive({
  title: '',
  category: '',
  amount: 0,
  occurDate: '',
  description: '',
  attachments: []
})

const expenseRules = {
  title: [{ required: true, message: '请输入费用标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择费用类别', trigger: 'change' }],
  amount: [{ required: true, message: '请输入费用金额', trigger: 'blur' }],
  occurDate: [{ required: true, message: '请选择发生日期', trigger: 'change' }]
}

// 项目列表
const projectList = ref([
  { id: 1, name: 'ERP系统开发项目' },
  { id: 2, name: '移动端APP开发' },
  { id: 3, name: '数据中台建设' }
])

// 计算属性
const filteredBudgetList = computed(() => {
  let filtered = budgetList.value
  
  if (budgetFilters.keyword) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(budgetFilters.keyword.toLowerCase())
    )
  }
  
  if (budgetFilters.category) {
    filtered = filtered.filter(item => item.category === budgetFilters.category)
  }
  
  if (budgetFilters.status) {
    filtered = filtered.filter(item => item.status === budgetFilters.status)
  }
  
  budgetPagination.total = filtered.length
  
  const start = (budgetPagination.currentPage - 1) * budgetPagination.pageSize
  const end = start + budgetPagination.pageSize
  
  return filtered.slice(start, end)
})

// 方法
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const getBudgetCategoryType = (category: string) => {
  const types = {
    labor: 'primary',
    equipment: 'success',
    material: 'warning',
    travel: 'info',
    other: 'default'
  }
  return types[category] || 'default'
}

const getBudgetCategoryLabel = (category: string) => {
  const labels = {
    labor: '人力成本',
    equipment: '设备费用',
    material: '材料费用',
    travel: '差旅费用',
    other: '其他费用'
  }
  return labels[category] || category
}

const getBudgetStatusType = (status: string) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    executing: 'primary',
    completed: 'info'
  }
  return types[status] || 'default'
}

const getBudgetStatusLabel = (status: string) => {
  const labels = {
    pending: '待审批',
    approved: '已批准',
    executing: '执行中',
    completed: '已完成'
  }
  return labels[status] || status
}

const getExpenseCategoryType = (category: string) => {
  const types = {
    travel: 'primary',
    meal: 'success',
    transport: 'warning',
    office: 'info',
    training: 'danger',
    other: 'default'
  }
  return types[category] || 'default'
}

const getExpenseCategoryLabel = (category: string) => {
  const labels = {
    travel: '差旅费',
    meal: '餐饮费',
    transport: '交通费',
    office: '办公用品',
    training: '培训费',
    other: '其他'
  }
  return labels[category] || category
}

const getExpenseStatusType = (status: string) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || 'default'
}

const getExpenseStatusLabel = (status: string) => {
  const labels = {
    pending: '待审批',
    approved: '已批准',
    rejected: '已拒绝'
  }
  return labels[status] || status
}

// 预算管理方法
const handleBudgetSearch = () => {
  budgetPagination.currentPage = 1
  // 这里会触发 filteredBudgetList 的重新计算
}

const resetBudgetFilters = () => {
  budgetFilters.keyword = ''
  budgetFilters.category = ''
  budgetFilters.status = ''
  budgetPagination.currentPage = 1
}

const handleBudgetSizeChange = (size: number) => {
  budgetPagination.pageSize = size
  budgetPagination.currentPage = 1
}

const handleBudgetCurrentChange = (page: number) => {
  budgetPagination.currentPage = page
}

const editBudget = (budget: any) => {
  Object.assign(budgetForm, budget)
  budgetDateRange.value = [budget.startDate, budget.endDate]
  showBudgetDialog.value = true
}

const viewBudgetDetail = (budget: any) => {
  ElMessage.info('查看预算详情功能开发中')
}

const deleteBudget = async (budget: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除预算项目"${budget.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = budgetList.value.findIndex(item => item.id === budget.id)
    if (index > -1) {
      budgetList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const saveBudget = async () => {
  if (!budgetFormRef.value) return
  
  try {
    await budgetFormRef.value.validate()
    budgetSaving.value = true
    
    // 处理日期范围
    if (budgetDateRange.value && budgetDateRange.value.length === 2) {
      budgetForm.startDate = budgetDateRange.value[0]
      budgetForm.endDate = budgetDateRange.value[1]
    }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (budgetForm.id) {
      // 编辑
      const index = budgetList.value.findIndex(item => item.id === budgetForm.id)
      if (index > -1) {
        budgetList.value[index] = { ...budgetForm }
      }
      ElMessage.success('预算更新成功')
    } else {
      // 新增
      const newBudget = {
        ...budgetForm,
        id: Date.now(),
        actualAmount: 0,
        variance: 0,
        status: 'pending'
      }
      budgetList.value.unshift(newBudget)
      ElMessage.success('预算创建成功')
    }
    
    showBudgetDialog.value = false
    resetBudgetForm()
  } catch (error) {
    console.error('保存预算失败:', error)
  } finally {
    budgetSaving.value = false
  }
}

const resetBudgetForm = () => {
  Object.assign(budgetForm, {
    id: null,
    projectId: '',
    name: '',
    category: '',
    budgetAmount: 0,
    description: '',
    startDate: '',
    endDate: ''
  })
  budgetDateRange.value = []
  if (budgetFormRef.value) {
    budgetFormRef.value.clearValidate()
  }
}

const exportBudgetData = () => {
  ElMessage.success('预算数据导出功能开发中')
}

// 费用审批方法
const viewExpenseDetail = (expense: any) => {
  ElMessage.info('查看费用详情功能开发中')
}

const approveExpense = async (expense: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要批准"${expense.title}"的费用申请吗？`,
      '确认批准',
      {
        confirmButtonText: '批准',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    expense.status = 'approved'
    expense.approver = '当前用户'
    ElMessage.success('费用申请已批准')
  } catch {
    ElMessage.info('已取消批准')
  }
}

const rejectExpense = async (expense: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要拒绝"${expense.title}"的费用申请吗？`,
      '确认拒绝',
      {
        confirmButtonText: '拒绝',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    expense.status = 'rejected'
    expense.approver = '当前用户'
    ElMessage.success('费用申请已拒绝')
  } catch {
    ElMessage.info('已取消拒绝')
  }
}

const submitExpense = async () => {
  if (!expenseFormRef.value) return
  
  try {
    await expenseFormRef.value.validate()
    expenseSaving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newExpense = {
      ...expenseForm,
      id: Date.now(),
      applicant: '当前用户',
      status: 'pending',
      submitDate: new Date().toISOString().split('T')[0],
      approver: ''
    }
    
    expenseList.value.unshift(newExpense)
    ElMessage.success('费用申请提交成功')
    
    showExpenseDialog.value = false
    resetExpenseForm()
  } catch (error) {
    console.error('提交费用申请失败:', error)
  } finally {
    expenseSaving.value = false
  }
}

const resetExpenseForm = () => {
  Object.assign(expenseForm, {
    title: '',
    category: '',
    amount: 0,
    occurDate: '',
    description: '',
    attachments: []
  })
  if (expenseFormRef.value) {
    expenseFormRef.value.clearValidate()
  }
}

// 图表初始化
const initCostTrendChart = () => {
  if (!costTrendChart.value) return
  
  const chart = echarts.init(costTrendChart.value)
  
  const option = {
    title: {
      text: '成本趋势',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        let result = params[0].name + '<br/>'
        params.forEach((param: any) => {
          result += `${param.seriesName}: ¥${param.value.toLocaleString()}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['预算', '实际支出'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => `¥${(value / 10000).toFixed(0)}万`
      }
    },
    series: [
      {
        name: '预算',
        type: 'line',
        data: [800000, 900000, 850000, 950000, 1000000, 1100000],
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '实际支出',
        type: 'line',
        data: [750000, 820000, 780000, 890000, 920000, 980000],
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initCostCategoryChart = () => {
  if (!costCategoryChart.value) return
  
  const chart = echarts.init(costCategoryChart.value)
  
  const option = {
    title: {
      text: '成本分类',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['人力成本', '设备费用', '材料费用', '差旅费用', '其他费用']
    },
    series: [
      {
        name: '成本分类',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1200000, name: '人力成本' },
          { value: 850000, name: '设备费用' },
          { value: 280000, name: '材料费用' },
          { value: 150000, name: '差旅费用' },
          { value: 120000, name: '其他费用' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initCostTrendChart()
    initCostCategoryChart()
  })
})
</script>

<style scoped>
.cost-control {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

/* 概览卡片样式 */
.overview-cards {
  margin-bottom: 24px;
}

.overview-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  margin-right: 16px;
}

.card-icon.budget {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.spent {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.remaining {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.variance {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

/* 图表区域样式 */
.charts-section {
  margin-bottom: 24px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 预算和费用区域样式 */
.budget-section,
.expense-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-filters {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 6px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 表格样式 */
.text-danger {
  color: #f56c6c;
}

.text-success {
  color: #67c23a;
}

/* 对话框样式 */
.upload-demo {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cost-control {
    padding: 12px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .card-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .card-icon {
    margin-right: 0;
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .card-value {
    font-size: 24px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .search-filters .el-row {
    flex-direction: column;
  }
  
  .search-filters .el-col {
    margin-bottom: 12px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 18px;
  }
  
  .card-value {
    font-size: 20px;
  }
  
  .chart-container {
    height: 200px;
  }
  
  .header-actions {
    flex-direction: column;
  }
}
</style>